package com.photoeditor.demo.ui.widget.beauty;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.demo.ui.widget.LoadingView;
import com.photoeditor.demo.ui.widget.image.attacher.CanvasPhotoViewAttacher;
import com.photoeditor.demo.ui.widget.image.attacher.IPhotoView;
import com.photoeditor.demo.util.AsyncTask;
import com.photoeditor.demo.util.ImageRectUtils;
import com.photoeditor.demo.util.beauty.WarpControl;
import com.photoeditor.demo.util.beauty.WrapUtil;

import java.util.ArrayList;

/**
 * 大眼的View
 */
public class BigEyesView extends AppCompatImageView implements IPhotoView {

    private Bitmap mOriginalBitmap;
    //原来的Bitmap
    private Bitmap mSrcBitmap;

    //用于标识是否初始化
    private boolean mIsInit = false;

    //本界面的Bound Rect
    private RectF mRect;

    //Drawable的Bound Rect  默认
    private RectF mDrawableRect;

    private final CanvasPhotoViewAttacher mAttacher;


    //#####################################

    //用于显示当前 点击位置的
    private RectF mTouchRect;
    private Rect mTcouchSrcRect;
    private RectF mCacheRect;
    private float mTouchSize;
    private boolean mTouchIsInLeft = true;
    private final static float MAX_TOUCH_SIZE = DeviceUtils.dip2px(ComponentContext.getContext(), 120);

    private ArrayList<WarpControl> mHistoryList;

    private float mCurRadius = MAX_RADIUS_PROGRESS;

    //是否绘制中间的圆  这个用于调整大眼的范围的时候
    private boolean mDrawCenterCircle = false;

    private final static int MAX_RADIUS_PROGRESS = DeviceUtils.dip2px(ComponentContext.getContext(), 27);
    private final static int MIN_RADIUS_PROGRESS = DeviceUtils.dip2px(ComponentContext.getContext(), 12);

    private Paint mRingPaint;
    private Paint mCirclePaint;
    private Paint mCenterPaint;
    private Paint mCommonPaint;
    private Paint mTouchOutSidePaint;

    private int mTouchOutSideBoundsWidth = DeviceUtils.dip2px(ComponentContext.getContext(), 2);

    private int mCenterJiaWidth;//中间十字的宽度

    private boolean mIsInDeal;
    private LoadingView mProgressDialog;

    //是否当前位置的圆  这个用于调整大眼的范围的时候
    private boolean mDrawCurrentCircle = false;

    private float mCurX;
    private float mCurY;
    /**
     * 初始化后显示的Drawable
     */
    private RectF mSupportDrawableRect;

    /**
     * 这个是图片的Bounds Drawable
     */
    private RectF mBaseDrawableRect;

    private int mTouchMode = MODE_NONE;
    private final static int MODE_NONE = 0;
    private final static int MODE_BIG_EYES = 1;

    private IBigEyeOperationListener mOperationListener;
    //#####################################

    private IStatusListener mStatusListener;


    private CanvasPhotoViewAttacher.OnMatrixChangedListener mMatrixChangeListener = new CanvasPhotoViewAttacher.OnMatrixChangedListener() {
        @Override
        public void onMatrixChanged(RectF rect) {
            if (mDrawableRect == null) {
                mDrawableRect = new RectF();
            }
            mDrawableRect.set(rect);
            mTouchSize = Math.min(mDrawableRect.width(), MAX_TOUCH_SIZE);
            mTouchSize = Math.min(mDrawableRect.height(), mTouchSize);
            if (mTouchIsInLeft) {
                mTouchRect.set(0, 0, mTouchSize, mTouchSize);
                mTouchRect.offset(mTouchOutSideBoundsWidth, mTouchOutSideBoundsWidth);
            } else {
                mTouchRect.set(mRect.width() - mTouchSize, 0, mRect.width(), mTouchSize);
                mTouchRect.offset(-mTouchOutSideBoundsWidth, -mTouchOutSideBoundsWidth);
            }
        }
    };

    public BigEyesView(Context context) {
        this(context, null, 0);
    }

    public BigEyesView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BigEyesView(Context context, AttributeSet attrs,
                       int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        super.setScaleType(ScaleType.MATRIX);
        mAttacher = new CanvasPhotoViewAttacher(this);
        setOnMatrixChangeListener(mMatrixChangeListener);
        initialize();
    }


    private void initialize() {
        setWillNotDraw(false);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        setMaximumScale(8.0f);
        setMediumScale(1.0f);
        mHistoryList = new ArrayList<>();
        mRingPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mRingPaint.setStyle(Paint.Style.STROKE);
        mRingPaint.setColor(Color.WHITE);
        mRingPaint.setStrokeWidth(DeviceUtils.dip2px(ComponentContext.getContext(), 2));

        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setStyle(Paint.Style.FILL);
        mCirclePaint.setColor(Color.parseColor("#33000000"));

        mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCenterPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mCenterPaint.setColor(Color.WHITE);
        mCenterPaint.setStrokeCap(Paint.Cap.ROUND);
        mCenterPaint.setStrokeJoin(Paint.Join.ROUND);

        mCommonPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);

        mTouchOutSidePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTouchOutSidePaint.setStyle(Paint.Style.STROKE);
        mTouchOutSidePaint.setColor(Color.WHITE);
        mTouchOutSidePaint.setStrokeWidth(mTouchOutSideBoundsWidth * 2);

        mCenterJiaWidth = DeviceUtils.dip2px(ComponentContext.getContext(), 2);

        mTouchRect = new RectF();
        mTcouchSrcRect = new Rect();
        mCacheRect = new RectF();
    }

    /**
     * 设置原图
     */
    public void setOriginalBitmap(Bitmap bm) {
        mOriginalBitmap = bm;
    }

    /**
     * @param bm
     * @param updateMatrix 是否重置当前的Matrix
     */
    public void setImageBitmap(Bitmap bm, boolean updateMatrix) {
        super.setImageBitmap(bm);
        if (mSrcBitmap == null || bm == null || (mSrcBitmap != bm && (mSrcBitmap.getWidth() != bm.getWidth() || mSrcBitmap.getHeight() != bm.getHeight()))) {
            mIsInit = false;
        }
        mSrcBitmap = bm;
        if (updateMatrix && null != mAttacher) {
            mAttacher.update();
        }
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        setImageBitmap(bm, false);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (!mIsInit && mSrcBitmap != null && !mSrcBitmap.isRecycled()) {
            init(ImageRectUtils.getViewRect(this));
        }
    }


    /**
     * 初始化这个类   这个方法在使用前必须调用 ！！！！！
     *
     * @param rect 整个View的Rect
     */
    public void init(RectF rect) {
        if (!mIsInit) {
            mRect = rect;
            countDrawableInitPosition(rect);
            mBaseDrawableRect = new RectF(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());
            mTouchSize = Math.min(mBaseDrawableRect.width(), MAX_TOUCH_SIZE);
            mTouchSize = Math.min(mBaseDrawableRect.height(), mTouchSize);
            mTouchRect.set(0, 0, mTouchSize, mTouchSize);
            mTouchRect.offset(mTouchOutSideBoundsWidth, mTouchOutSideBoundsWidth);
            mTouchIsInLeft = true;
            mIsInit = true;
        }
    }

    /**
     * 先绘制未选中的  然后绘制选中的
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!mIsInit || mSrcBitmap == null || mSrcBitmap.isRecycled()) {
            return;
        }

        int saveCount = canvas.save();
        float centerX = Math.max(mDrawableRect.left, mCurX);
        centerX = Math.min(mDrawableRect.right, centerX);
        float centerY = Math.max(mDrawableRect.top, mCurY);
        centerY = Math.min(mDrawableRect.bottom, centerY);

        canvas.clipRect(mDrawableRect);//裁剪到当前显示区域内

        if (mDrawCenterCircle) {
            mCacheRect.set(mRect);
            mCacheRect.offset(-mRect.left, -mRect.top);
            drawCircleFlag(canvas, mCacheRect.centerX(), mCacheRect.centerY());
        }

        if (mDrawCurrentCircle) {
            drawCircleFlag(canvas, centerX, centerY);
        }
        canvas.restoreToCount(saveCount);
        if (mDrawCurrentCircle) {
            int saveCount2 = canvas.save();
            if (mTouchRect.contains(centerX, centerY)) {
                if (mTouchIsInLeft) {
                    mTouchIsInLeft = false;
                    mTouchRect.set(mRect.width() - mTouchSize, 0, mRect.width(), mTouchSize);
                    mTouchRect.offset(-mTouchOutSideBoundsWidth, -mTouchOutSideBoundsWidth);
                } else {
                    mTouchIsInLeft = true;
                    mTouchRect.set(0, 0, mTouchSize, mTouchSize);
                    mTouchRect.offset(mTouchOutSideBoundsWidth, mTouchOutSideBoundsWidth);
                }
            }
            canvas.clipRect(mTouchRect.left - mTouchOutSideBoundsWidth, mTouchRect.top - mTouchOutSideBoundsWidth
                    , mTouchRect.right + mTouchOutSideBoundsWidth, mTouchRect.bottom + mTouchOutSideBoundsWidth);//裁剪到当前显示区域内
            float radius = mTouchSize / 2;
            mCacheRect.set(centerX - radius, centerY - radius, centerX + radius, centerY + radius);
            float dx = 0, dy = 0;//下面的代码用于保证框内一定会显示完全
            if (mCacheRect.left < mDrawableRect.left) {
                dx = mDrawableRect.left - mCacheRect.left;
            } else if (mCacheRect.right > mDrawableRect.right) {
                dx = mDrawableRect.right - mCacheRect.right;
            }
            if (mCacheRect.top < mDrawableRect.top) {
                dy = mDrawableRect.top - mCacheRect.top;
            } else if (mCacheRect.bottom > mDrawableRect.bottom) {
                dy = mDrawableRect.bottom - mCacheRect.bottom;
            }
            mCacheRect.offset(dx, dy);
            //这个touchCenterX touchCenterY就是小图中的十字的中心点
            float touchCenterX = mTouchRect.centerX() - dx;
            float touchCenterY = mTouchRect.centerY() - dy;

            float scale = mDrawableRect.width() / mBaseDrawableRect.width();
            mCacheRect.offset(-mDrawableRect.left, -mDrawableRect.top);
            mTcouchSrcRect.set((int) (mCacheRect.left / scale), (int) (mCacheRect.top / scale), (int) (mCacheRect.right / scale), (int) (mCacheRect.bottom / scale));
            canvas.drawBitmap(mSrcBitmap, mTcouchSrcRect, mTouchRect, mCommonPaint);
            drawCircleFlag(canvas, touchCenterX, touchCenterY);
            canvas.drawRect(mTouchRect.left - mTouchOutSideBoundsWidth, mTouchRect.top - mTouchOutSideBoundsWidth
                    , mTouchRect.right + mTouchOutSideBoundsWidth, mTouchRect.bottom + mTouchOutSideBoundsWidth, mTouchOutSidePaint);
            canvas.restoreToCount(saveCount2);
        }
    }

    /**
     * @param canvas
     * @param centerX
     * @param centerY
     */
    private void drawCircleFlag(Canvas canvas, float centerX, float centerY) {//保证一定绘制在内部
        canvas.drawCircle(centerX, centerY, mCurRadius, mCirclePaint);
        canvas.drawCircle(centerX, centerY, mCurRadius, mRingPaint);
        float rectWidth = mCurRadius * 2 / 3;
        canvas.drawRect(centerX - rectWidth / 2, centerY - mCenterJiaWidth / 2, centerX + rectWidth / 2, centerY + mCenterJiaWidth / 2, mCenterPaint);
        canvas.drawRect(centerX - mCenterJiaWidth / 2, centerY - rectWidth / 2, centerX + mCenterJiaWidth / 2, centerY + rectWidth / 2, mCenterPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!mIsInit) return super.onTouchEvent(event);
        if (event.getPointerCount() != 1) {
            setDrawCurrentCircle(false);
            mAttacher.onTouch(this, event);
            mTouchMode = MODE_NONE;
        } else {//单指点击的
            WarpControl curBean = new WarpControl();
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN) {
                mTouchMode = MODE_BIG_EYES;
                mCurX = event.getX();
                mCurY = event.getY();
                setDrawCurrentCircle(true);
                mAttacher.onTouch(this, event);
                return true;
            } else if (action == MotionEvent.ACTION_MOVE) {
                mCurX = event.getX();
                mCurY = event.getY();
                if (mTouchMode == MODE_BIG_EYES) {
                    invalidate();
                } else {
                    mAttacher.onTouch(this, event);
                }
            } else if (action == MotionEvent.ACTION_UP) {
                setDrawCurrentCircle(false);
                if (mTouchMode == MODE_BIG_EYES) {
                    mCurX = event.getX();
                    mCurY = event.getY();
                    float scale = mBaseDrawableRect.width() / mDrawableRect.width();
                    int x = (int) ((mCurX - mDrawableRect.left) * scale);
                    int y = (int) ((mCurY - mDrawableRect.top) * scale);
                    curBean.orig_x = x;
                    curBean.orig_y = y;
                    curBean.max_dist = getCurRadius();
                    curBean.max_dist_sq = curBean.max_dist * curBean.max_dist;
                    //强度在这里设置
                    doEyeBigger(mSrcBitmap, curBean);
                } else {
                    mAttacher.onTouch(this, event);
                }
                mTouchMode = MODE_NONE;
            } else {
                mTouchMode = MODE_NONE;
                setDrawCurrentCircle(false);
                mAttacher.onTouch(this, event);
            }
        }
        return super.onTouchEvent(event);
    }

    /**
     * 获取当前缩放下 合适的半径
     *
     * @return
     */
    private float getCurRadius() {
        //最开始到现在的缩放值
        float scale = mBaseDrawableRect.width() / mDrawableRect.width();
        return mCurRadius * scale;
    }

    /**
     * 0 - 100
     *
     * @param progress
     */
    public void setProgress(int progress) {
        mCurRadius = progress / 100f * (MAX_RADIUS_PROGRESS - MIN_RADIUS_PROGRESS) + MIN_RADIUS_PROGRESS;
        invalidate();
    }

    public void setDrawCenterCircle(boolean drawCircle) {
        mDrawCenterCircle = drawCircle;
        invalidate();
    }

    public void setDrawCurrentCircle(boolean drawCurrentCircle) {
        this.mDrawCurrentCircle = drawCurrentCircle;
        if (mStatusListener != null) {
            mStatusListener.onStatusChanged(drawCurrentCircle);
        }
        invalidate();
    }

    public boolean isDrawCurrentCircle() {
        return mDrawCurrentCircle;
    }

    public void setOperationListener(IBigEyeOperationListener operationListener) {
        this.mOperationListener = operationListener;
    }

    public void setStatusListener(IStatusListener listener) {
        mStatusListener = listener;
    }

    /**
     * 放大操作
     */
    private void doEyeBigger(final Bitmap srcBitmap, final WarpControl curBean) {
        if (!mIsInDeal) {
            if (mProgressDialog != null) {
                mProgressDialog.startLoading();
            }
            mIsInDeal = true;
            AsyncTask.DUAL_THREAD_EXECUTOR.execute(new Runnable() {
                @Override
                public void run() {
                    final Bitmap bitmap = WrapUtil.imageScale(srcBitmap, curBean, 0.3f);
                    post(new Runnable() {
                        @Override
                        public void run() {
                            onDealOver(bitmap, curBean);
                        }
                    });
                }
            });
        }
    }

    /**
     * 处理完成后
     *
     * @param bitmap
     * @param curBean
     */
    private void onDealOver(final Bitmap bitmap, final WarpControl curBean) {
        mHistoryList.add(curBean);
        if (mHistoryList.size() > 3) {
            mHistoryList.remove(0);
        }
        setImageBitmap(bitmap, false);
        mIsInDeal = false;
        mProgressDialog.stopLoading();
        if (mOperationListener != null) {
            mOperationListener.onOperationSizeChanged(mHistoryList.size());
        }
    }

    /**
     * 是否改变
     *
     * @return
     */
    public boolean isChanged() {
        return (mHistoryList.size() != 0);
    }

    public void showOriginalBitmap() {
        super.setImageBitmap(mOriginalBitmap);
    }

    public void showEffect() {
        setImageBitmap(mSrcBitmap, false);
    }

    /**
     * 回退到上一步
     */
    public void undo() {
        if (!mIsInDeal && mHistoryList.size() > 0) {
            if (mProgressDialog != null) {
                mProgressDialog.startLoading();
            }
            mIsInDeal = true;
            mHistoryList.remove(mHistoryList.size() - 1);
            final ArrayList<WarpControl> list = new ArrayList<WarpControl>(mHistoryList);
            final Bitmap oldBitmap = mOriginalBitmap;
            AsyncTask.DUAL_THREAD_EXECUTOR.execute(new Runnable() {
                @Override
                public void run() {
                    Bitmap bitmap = oldBitmap;
                    int size = list.size();
                    for (int i = 0; i < size; i++) {
                        WarpControl bean = list.get(i);
                        bitmap = WrapUtil.imageScale(bitmap, bean, 0.3f);
                    }
                    final Bitmap newBitmap = bitmap;
                    post(new Runnable() {
                        @Override
                        public void run() {
                            setImageBitmap(newBitmap, false);
                            mIsInDeal = false;
                            mProgressDialog.stopLoading();
                            if (mOperationListener != null) {
                                mOperationListener.onOperationSizeChanged(mHistoryList.size());
                            }
                        }
                    });
                }
            });
        }
    }

    public void setProgressDialog(LoadingView progressDialog) {
        mProgressDialog = progressDialog;
    }

    public Bitmap getCurBitmap() {
        if (mSrcBitmap != null) {
            return mSrcBitmap;
        }
        return mOriginalBitmap;
    }

    /**
     * 清除所有的
     */
    public void reset() {
        mOriginalBitmap = null;
        setImageBitmap(null);
        mHistoryList.clear();
        if (mOperationListener != null) {
            mOperationListener.onOperationSizeChanged(mHistoryList.size());
        }
    }

    /**
     * 用于获取合成好的图片
     * mDrawableRect 是放大后的 Rect  ,Emoji的效果也是放大后的所以需要这样
     *
     * @return
     */
    public Bitmap getDstBitmap() {
        if (mSrcBitmap != null && !mSrcBitmap.isRecycled()) {
        }
        return mSrcBitmap;
    }


    ///########################################

    @Override
    public void setPhotoViewRotation(float rotationDegree) {
        mAttacher.setRotationTo(rotationDegree);
    }

    @Override
    public void setRotationTo(float rotationDegree) {
        mAttacher.setRotationTo(rotationDegree);
    }

    @Override
    public void setRotationBy(float rotationDegree) {
        mAttacher.setRotationBy(rotationDegree);
    }

    @Override
    public boolean canZoom() {
        return mAttacher.canZoom();
    }

    @Override
    public RectF getDisplayRect() {
        return mAttacher.getDisplayRect();
    }

    @Override
    public Matrix getDisplayMatrix() {
        return mAttacher.getDrawMatrix();
    }

    @Override
    public boolean setDisplayMatrix(Matrix finalRectangle) {
        return mAttacher.setDisplayMatrix(finalRectangle);
    }

    @Override
    @Deprecated
    public float getMinScale() {
        return getMinimumScale();
    }

    @Override
    public float getMinimumScale() {
        return mAttacher.getMinimumScale();
    }

    @Override
    @Deprecated
    public float getMidScale() {
        return getMediumScale();
    }

    @Override
    public float getMediumScale() {
        return mAttacher.getMediumScale();
    }

    @Override
    @Deprecated
    public float getMaxScale() {
        return getMaximumScale();
    }

    @Override
    public float getMaximumScale() {
        return mAttacher.getMaximumScale();
    }

    @Override
    public float getScale() {
        return mAttacher.getScale();
    }

    @Override
    public ScaleType getScaleType() {
        return mAttacher.getScaleType();
    }

    @Override
    public void setAllowParentInterceptOnEdge(boolean allow) {
        mAttacher.setAllowParentInterceptOnEdge(allow);
    }

    @Override
    @Deprecated
    public void setMinScale(float minScale) {
        setMinimumScale(minScale);
    }

    @Override
    public void setMinimumScale(float minimumScale) {
        mAttacher.setMinimumScale(minimumScale);
    }

    @Override
    @Deprecated
    public void setMidScale(float midScale) {
        setMediumScale(midScale);
    }

    @Override
    public void setMediumScale(float mediumScale) {
        mAttacher.setMediumScale(mediumScale);
    }

    @Override
    @Deprecated
    public void setMaxScale(float maxScale) {
        setMaximumScale(maxScale);
    }

    @Override
    public void setMaximumScale(float maximumScale) {
        mAttacher.setMaximumScale(maximumScale);
    }


    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
        if (null != mAttacher) {
            mAttacher.update();
        }
    }

    @Override
    public void setImageURI(Uri uri) {
        super.setImageURI(uri);
        if (null != mAttacher) {
            mAttacher.update();
        }
    }

    @Override
    public void setOnMatrixChangeListener(CanvasPhotoViewAttacher.OnMatrixChangedListener listener) {
        mAttacher.setOnMatrixChangeListener(listener);
    }

    @Override
    public void setOnLongClickListener(OnLongClickListener l) {
        mAttacher.setOnLongClickListener(l);
    }

    @Override
    public void setOnPhotoTapListener(CanvasPhotoViewAttacher.OnPhotoTapListener listener) {
        mAttacher.setOnPhotoTapListener(listener);
    }

    @Override
    public CanvasPhotoViewAttacher.OnPhotoTapListener getOnPhotoTapListener() {
        return mAttacher.getOnPhotoTapListener();
    }

    @Override
    public void setOnViewTapListener(CanvasPhotoViewAttacher.OnViewTapListener listener) {
        mAttacher.setOnViewTapListener(listener);
    }

    @Override
    public CanvasPhotoViewAttacher.OnViewTapListener getOnViewTapListener() {
        return mAttacher.getOnViewTapListener();
    }

    @Override
    public void setScale(float scale) {
        mAttacher.setScale(scale);
    }

    @Override
    public void setScale(float scale, boolean animate) {
        mAttacher.setScale(scale, animate);
    }

    @Override
    public void setScale(float scale, float focalX, float focalY, boolean animate) {
        mAttacher.setScale(scale, focalX, focalY, animate);
    }

    @Override
    public void setScaleType(ScaleType scaleType) {
        if (null != mAttacher) {
            mAttacher.setScaleType(scaleType);
        }
    }

    @Override
    public void setZoomable(boolean zoomable) {
        mAttacher.setZoomable(zoomable);
    }

    @Override
    public Bitmap getVisibleRectangleBitmap() {
        return mAttacher.getVisibleRectangleBitmap();
    }

    @Override
    public void setZoomTransitionDuration(int milliseconds) {
        mAttacher.setZoomTransitionDuration(milliseconds);
    }

    @Override
    public IPhotoView getIPhotoViewImplementation() {
        return mAttacher;
    }

    @Override
    public void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener newOnDoubleTapListener) {
        mAttacher.setOnDoubleTapListener(newOnDoubleTapListener);
    }

    @Override
    public float getBaseScale() {
        return mAttacher.getBaseScale();
    }

    @Override
    protected void onDetachedFromWindow() {
        mAttacher.cleanup();
        super.onDetachedFromWindow();
    }

    /**
     * 这个方法要在Init后调用
     */
    private void countDrawableInitPosition(RectF viewRect) {
        mSupportDrawableRect = new RectF();
        float width = mSrcBitmap.getWidth();
        float height = mSrcBitmap.getHeight();

        float vW = viewRect.width();
        float vH = viewRect.height();

        float w, h;

        if (width / height > vW / vH) {//宽顶着
            w = vW;
            h = w / width * height;
        } else {//高顶着
            h = vH;
            w = h / height * width;
        }

        mSupportDrawableRect.left = (vW - w) / 2 + viewRect.left;
        mSupportDrawableRect.top = (vH - h) / 2 + viewRect.top;
        mSupportDrawableRect.right = mSupportDrawableRect.left + w;
        mSupportDrawableRect.bottom = mSupportDrawableRect.top + h;
    }
}
